package com.yuma.rabbitmq.reconsumerconsumer.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class Consumer {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(queues = "queue0")
    public void receive(String msg, Message message, Channel channel) throws IOException {
        if (msg == null ){
            // 拒绝了
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        }
        // 从message中得到此message的id当 幂等性的key  setnx
        String messageId = message.getMessageProperties().getMessageId(); // 123456789
        String redisKey = "messageId:" + messageId;
        // setIfAbsent如果不存在key则会设置成功返回true (代表是第一次操作); 否则存在则设置不成功，返回false（已经第二次进来了）
        if (redisTemplate.opsForValue().setIfAbsent(redisKey, messageId, 60, TimeUnit.SECONDS)){

            System.out.println("第一个设置key成功");
            // 成功消费掉
            System.out.println("成功消费掉: " + msg);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }else{
            System.out.println("第二此设置key失败");
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }
    }
}